package com.xzg.erp.product.config;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.xzg.erp.common.Constants;
import com.xzg.erp.product.entity.Product;
import com.xzg.erp.product.entity.dto.ProductDto;
import com.xzg.erp.product.service.IProductService;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

public class ProductDataListener implements ReadListener<ProductDto> {

    private IProductService productService;

    // 相同编码直接覆盖
    private List<Product> replace = new ArrayList<>();
    // 相同编码返回未覆盖产品编码即可
    private List<Product> notReplace = new ArrayList<>();
    private LocalDateTime now = LocalDateTime.now();
    private int userId = StpUtil.getLoginIdAsInt();

    private String result = Constants.IMPORT_SUCCESS;

    public ProductDataListener(IProductService productService){
        this.productService = productService;
    }

    @Override
    public void invoke(ProductDto productDto, AnalysisContext analysisContext) {
        if (Constants.YES.equals(productDto.getReplace())) {
            replace.add(createProduct(productDto));
        }else{
            notReplace.add(createProduct(productDto));
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        Map<String, Set<String>> replaceMap = productService.importProduct(replace, notReplace);
        this.result = this.result +" "+ replaceMap.entrySet().stream()
                .map(entry ->
                        entry.getKey() + ":" + String.join(",", entry.getValue())
                )
                .collect(Collectors.joining(" "));
    }

    private Product createProduct(ProductDto productDto) {
        Product product = BeanUtil.copyProperties(productDto, Product.class);
        product.setCreatedBy(userId);
        product.setCreatedAt(now);
        product.setUpdatedBy(userId);
        product.setUpdatedAt(now);
        return product;
    }

    public String getResult(){
        return this.result;
    }
}
